此兩種方法其實與 user 的部份大致雷同,也是先經過 middleware 檢查後才可執行。
update
檢查使用者輸入 ( 同樣並非每一項都是必填 )
$rules = [
'title' => 'string|min:2|max:500',
'content' => 'string|min:2|max:1500'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response(['message' => $validator->errors()]);
}
確認該使用者存在與否,若存在就做修改貼文的動作
$post = Post::find($id);
if(!is_null($post)){
$post->update($request->only(['title', 'content']));
return response(['data' => $post]);
}
return response(['message' => 'Post not found!']);
完整程式碼
*PostsController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;
use App\User;
class PostsController extends Controller
{
public function update(Request $request, $id)
{
$rules = [
'title' => 'string|min:2|max:500',
'content' => 'string|min:2|max:1500'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response(['message' => $validator->errors()]);
}
$post = Post::find($id);
if(!is_null($post)){
$post->update($request->only(['title', 'content']));
return response(['data' => $post]);
}
return response(['message' => 'Post not found!']);
}
}
destroy
此處也是檢查該貼文存在與否,存在的話就可刪除
完整程式碼
*PostsController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;
use App\User;
class PostsController extends Controller
{
public function destroy($id)
{
$post = Post::find($id);
if(!is_null($post)){
$post->delete();
return response(['message' => 'Post deleted!!']);
}
return response(['message' => 'Post not found!']);
}
}
為了簡潔重複過的步驟,此處不一一做錯誤的測試
update
delete
然而到此為止依舊有些奇怪,詳情請見下一篇。